package com.pimee.service.admin.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.pimee.common.util.DateUtil;
import com.pimee.common.util.RowBoundUtil;
import com.pimee.common.util.StringUtils;
import com.pimee.mapper.SysDeptMapper;
import com.pimee.mapper.SysUnitMapper;
import com.pimee.model.SysDept;
import com.pimee.model.SysUnit;
import com.pimee.service.BaseService;
import com.pimee.service.admin.ISysUnitService;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Slf4j
@Service
public class SysUnitService extends BaseService<SysUnit> implements ISysUnitService {

	@Autowired
	private SysUnitMapper sysUnitMapper;
	@Autowired
	private SysDeptMapper sysDeptMapper;
	
	@Override
	public PageInfo<SysUnit> pageList(Map<String, Object> params) {
		log.info("===> OEM列表分页查询...");
		Page<?> page = startPage(params);// 设置分页
		int pageNum = page.getPageNum();
		int pageSize = page.getPageSize();
		RowBounds rowBounds = RowBoundUtil.getRowBounds(pageNum, pageSize);
		Example example = new Example(SysUnit.class);
		Criteria criteria = example.createCriteria();
		String unitName = (String) params.get("unitName");
		if(StringUtils.isNotBlank(unitName)) {
			criteria.andLike("unitName", "%".concat(unitName).concat("%"));
		}
		List<SysUnit> list = sysUnitMapper.selectByExampleAndRowBounds(example, rowBounds);
		return new PageInfo<>(list);
	}
	
	@Override
	public void insertUnit(SysUnit param) {
		Date now = DateUtil.now();
		param.setCreateTime(now);
		param.setUpdateTime(now);
		this.saveNotNull(param);
		
		// 同时新增顶级代理
		SysDept sysDept = new SysDept();
		sysDept.setCreateBy(param.getCreateBy());
		sysDept.setUpdateBy(param.getCreateBy());
		sysDept.setUnitId(param.getUnitId());
		sysDept.setDeptName(param.getUnitName());
		sysDept.setParentId(0l);// 顶级代理
		sysDept.setPhone(param.getPhone());
		sysDept.setCreateTime(now);
		sysDept.setUpdateTime(now);
		sysDeptMapper.insertSelective(sysDept);
	}

	@Override
	public void updateUnit(SysUnit param) {
		Date now = DateUtil.now();
		param.setUpdateTime(now);
		this.updateNotNull(param);
		
		// 同时修改顶级代理名称
		SysDept sysDept = new SysDept();
		sysDept.setDeptName(param.getUnitName());
		sysDept.setUpdateTime(now);
		Example example = new Example(SysDept.class);
		example.createCriteria().andEqualTo("parentId", 0l).andEqualTo("unitId", param.getUnitId());
		sysDeptMapper.updateByExampleSelective(sysDept, example);
	}
	
}
